﻿#include "waitsave.h"
#include <QDebug>
#include <QThread>
#include <QFile>
#include <QDateTime>
#include <QPixmap>
#include <QStorageInfo>
#include <QDir>
#include <QtEndian>
#include <QtConcurrent>

#define IMAGE_WIDTCH        8424
#define IMAGE_HEIGHT        6032
#define DMA_BLOCK_SIZE      2*IMAGE_WIDTCH*IMAGE_HEIGHT
#define DMA_BLOCK_NUM       1
#define IMAGE_SIZE          DMA_BLOCK_SIZE*DMA_BLOCK_NUM

unsigned int WaitSave::num_trigger_ = 0;

WaitSave::WaitSave()
{
    pworkThread = new SaveThread();
    pworkThread->start();
    saveThread = new CompressSendThread();
    connect(saveThread,&CompressSendThread::CompressPictureOver,this,&WaitSave::pictureOver,Qt::DirectConnection);
    saveThread->start();


}

WaitSave::~WaitSave()
{
    pworkThread->stop();
    pworkThread->quit();
    pworkThread->wait(1000);
    saveThread->stop();
    saveThread->quit();
    saveThread->wait(1000);
}



void WaitSave::saveAndTrans()
{


    unsigned int num = axil_cmd_get(axil_cmd_user,USER_TRIGGER_CNT);
    if(num != num_trigger_){
//        qDebug() << num << "trigger success!!!" << QDateTime::currentDateTime().toString("yyyyy-MM-dd hh:mm:ss.zzz");
        num_trigger_ = num;
    }
    //    while(1){
    //        qDebug() << "dma_success_flag start" << *dma_success_flag;
    //        QThread::msleep(1);
    if(*dma_success_flag == false){

//        qDebug() << "in savehandle" << QDateTime::currentDateTime().toString("yyyyy-MM-dd hh:mm:ss.zzz");
//        qDebug() << (*dma_success_flag);
        //            qDebug() << "axidma_dev"<<axidma_dev<<"rx_chans"<<rx_chans<<"rx_buf"<<rx_buf;
        (*dma_success_flag) = true;
//        qDebug() << "dma_success_flag pass";
        axidma_oneway_transfer(axidma_dev,rx_chans->data[0],rx_buf,DMA_BLOCK_SIZE,false);
        axil_cmd_set(axil_cmd_user,USER_DMA_RDY,0x1);
        //    memcpy(&image_mid0[DMA_BLOCK_SIZE],(unsigned char *)rx_buf,DMA_BLOCK_SIZE);
        memcpy(image_mid0,(unsigned char *)rx_buf,DMA_BLOCK_SIZE);
        //        axidma_stop_transfer(axidma_dev,rx_chans->data[0]);
        (*fd_name)++;
        // End timing
        // Compute the throughput of each channel

      QByteArray byteArray((char*)image_mid0, 101627136);
      QFile file("/mnt/output.raw");
      if(file.open(QIODevice::WriteOnly)){
          file.write(byteArray);
      }
      file.close();
//      qDebug() << byteArray.toHex();
        image = QImage(image_mid0,IMAGE_WIDTCH,IMAGE_HEIGHT,QImage::Format_Grayscale16);
        //上传缩略图
        saveThread->addTask(new CompressSend(image,image_mid0,list,cameraIndex,cameraInfo.picStartX, cameraInfo.picStartY, cameraInfo.picWidth, cameraInfo.picHeight,qFromLittleEndian<quint32>(receive_photo_message_.constData())));
        //        image = QImage("/mnt/mnt2/111.tiff");//测试图像传输使用
//        qDebug() << "getImage" << QDateTime::currentDateTime().toString("yyyyy-MM-dd hh:mm:ss.zzz");
        //    image = image.mirrored(true, false);
        QList<QStorageInfo> storageInfoList = QStorageInfo::mountedVolumes();
        foreach (QStorageInfo storage, storageInfoList) {
//            qDebug() << storage;
            if(storage.rootPath().contains(delete_path_)){
                qDebug() << storage.bytesAvailable()/1048576 << "delete_image";
                if(surplus_storage_ > storage.bytesAvailable()/1048576){
                    qDebug() << "delete_image";
                    QtConcurrent::run(this,&WaitSave::deletePhoto);
                }
            }
        }

        if(receive_photo_message_.isEmpty()){
            QThread::usleep(10000);
            if(receive_photo_message_.isEmpty()){
                load1 = path1 + QString("%1%2%3").arg("gtest",QString::number(*cameraIndex),".tif");
                load2 = path2 + QString("%1%2%3").arg("gtest",QString::number(*cameraIndex),".tif");
            }else{
                assist_message = receive_photo_message_;//目前为传入的全部信息
                receive_photo_message_.clear();
                load1 = path1 +  QString("AFC_001_%1%2%3_%4%5%6_%7_%8_CMOS%9.tif")
                        .arg(assist_message[4]+2000).arg(assist_message[5],2,10,QChar('0')).arg(assist_message[6],2,10,QChar('0'))
                        .arg(assist_message[7],2,10,QChar('0')).arg(assist_message[8],2,10,QChar('0')).arg(assist_message[9],2,10,QChar('0'))
//                         .arg(qFromLittleEndian<quint32>(assist_message.constData()))
                        .arg(QString("%1").arg(qFromLittleEndian<quint32>(assist_message.constData())).right(4))
                        .arg(*cameraIndex,4,10,QChar('0'))
                        .arg(device_num_,2,10,QChar('0'));
                load2 = path2 +  QString("AFC_001_%1%2%3_%4%5%6_%7_%8_CMOS%9.tif")
                        .arg(assist_message[4]+2000).arg(assist_message[5],2,10,QChar('0')).arg(assist_message[6],2,10,QChar('0'))
                        .arg(assist_message[7],2,10,QChar('0')).arg(assist_message[8],2,10,QChar('0')).arg(assist_message[9],2,10,QChar('0'))
                         .arg(QString("%1").arg(qFromLittleEndian<quint32>(assist_message.constData())).right(4))
                        .arg(*cameraIndex,4,10,QChar('0'))
                        .arg(device_num_,2,10,QChar('0'));
//                load1 = path1 + QString("%1%2%3%4%5%6%7%8%9").arg("AFC_001_",assist_message.mid(8,6),"_",assist_message.mid(14,6),"_",QString("%1").arg(*cameraIndex,4,10,QChar('0')),"_",QString("%1").arg(device_num_,2,10,QChar('0')),".tiff");
//                load2 = path2 + QString("%1%2%3%4%5%6%7%8%9").arg("AFC_001_",assist_message.mid(8,6),"_",assist_message.mid(14,6),"_",QString("%1").arg(*cameraIndex,4,10,QChar('0')),"_",QString("%1").arg(device_num_,2,10,QChar('0')),".tiff");
            }
        }else{
            assist_message = receive_photo_message_;//目前为传入的全部信息
//            qDebug() << assist_message.toHex() << assist_message.size()<< "sssssssss";
            receive_photo_message_.clear();
           load1 = path1 +  QString("AFC_001_%1%2%3_%4%5%6_%7_%8_CMOS%9.tif")
                   .arg(assist_message[4]+2000).arg(assist_message[5],2,10,QChar('0')).arg(assist_message[6],2,10,QChar('0'))
                   .arg(assist_message[7],2,10,QChar('0')).arg(assist_message[8],2,10,QChar('0')).arg(assist_message[9],2,10,QChar('0'))
                    .arg(QString("%1").arg(qFromLittleEndian<quint32>(assist_message.constData())).right(4))
                   .arg(*cameraIndex,4,10,QChar('0'))
                   .arg(device_num_,2,10,QChar('0'));
           load2 = path2 +  QString("AFC_001_%1%2%3_%4%5%6_%7_%8_CMOS%9.tif")
                   .arg(assist_message[4]+2000).arg(assist_message[5],2,10,QChar('0')).arg(assist_message[6],2,10,QChar('0'))
                   .arg(assist_message[7],2,10,QChar('0')).arg(assist_message[8],2,10,QChar('0')).arg(assist_message[9],2,10,QChar('0'))
                    .arg(QString("%1").arg(qFromLittleEndian<quint32>(assist_message.constData())).right(4))
                   .arg(*cameraIndex,4,10,QChar('0'))
                   .arg(device_num_,2,10,QChar('0'));
//            load1 = path1 + QString("%1%2%3%4%5%6%7%8%9").arg("AFC_001_",assist_message.mid(4,3),"_",assist_message.mid(14,6),"_",QString("%1").arg(*cameraIndex,4,10,QChar('0')),"_",QString("%1").arg(device_num_,2,10,QChar('0')),".tiff");
//            load2 = path2 + QString("%1%2%3%4%5%6%7%8%9").arg("AFC_001_",assist_message.mid(8,6),"_",assist_message.mid(14,6),"_",QString("%1").arg(*cameraIndex,4,10,QChar('0')),"_",QString("%1").arg(device_num_,2,10,QChar('0')),".tiff");
        }
        //            qDebug() << cameraInfo.picStartX << cameraInfo.picStartY << cameraInfo.picWidth << cameraInfo.picHeight;
        if(cameraInfo.exposureMode == CameraSpace::ShowAndSave){
            if(IMAGE_WIDTCH != cameraInfo.picWidth || IMAGE_HEIGHT != cameraInfo.picHeight){
                QRect temp_rect = QRect(cameraInfo.picStartX, cameraInfo.picStartY, cameraInfo.picWidth, cameraInfo.picHeight);
                qDebug() << cameraInfo.picStartX << cameraInfo.picStartY << cameraInfo.picWidth << cameraInfo.picHeight;
                QImage temp_img = image.copy(temp_rect);
                if(cameraInfo.saveLocation == CameraSpace::All){
                    pworkThread->addTask(new SaveTask(temp_img,load1,assist_message));
                    pworkThread->addTask(new SaveTask(temp_img,load2,assist_message));
                }else if(cameraInfo.saveLocation == CameraSpace::In){
                    pworkThread->addTask(new SaveTask(temp_img,load1,assist_message));
                }else if(cameraInfo.saveLocation == CameraSpace::Out){
                    pworkThread->addTask(new SaveTask(temp_img,load2,assist_message));
                }

            }else{
                if(cameraInfo.saveLocation == CameraSpace::All){
                    pworkThread->addTask(new SaveTask(image,load1,assist_message));
                    pworkThread->addTask(new SaveTask(image,load2,assist_message));
                }else if(cameraInfo.saveLocation == CameraSpace::In){
                    pworkThread->addTask(new SaveTask(image,load1,assist_message));
                }else if(cameraInfo.saveLocation == CameraSpace::Out){
                    pworkThread->addTask(new SaveTask(image,load2,assist_message));
                }
            }
//            qDebug() << "end.........";
        }
        //            if(cameraInfo.exposureMode == CameraSpace::OnlySave){
//        QImage send_image;
//        QPixmap p;
//        if(IMAGE_WIDTCH != cameraInfo.picWidth || IMAGE_HEIGHT != cameraInfo.picHeight){
//            QRect temp_rect = QRect(cameraInfo.picStartX, cameraInfo.picStartY, cameraInfo.picWidth, cameraInfo.picHeight);
//            send_image = image.copy(temp_rect);
//            //                    CompressSend* compress = new CompressSend(send_image,list,cameraIndex);
//            //                    saveThread->addTask(compress);
//            saveThread->addTask(new CompressSend(send_image,list,cameraIndex));
//            //                qDebug() << "copy finish" << QDateTime::currentDateTime().toString("yyyyy-MM-dd hh:mm:ss.zzz");
//            //                send_image = send_image.scaled(800, 600,Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

//        }else{
//            send_image = image;
//            saveThread->addTask(new CompressSend(send_image,list,cameraIndex));

//        }
    }
}

void WaitSave::deletePhoto()
{
    QDir path(delete_path_);
    path.setFilter(QDir::Files);//设置过滤器过滤类型
    path.setSorting(QDir::Name);//根据时间排序，末尾为最早时间
    QStringList string_list = path.entryList();
    for(int i = 0; i < 100; ++i){
//        qDebug() << string_list.at(i);
        path.remove(string_list.at(i));//删除文件
    }
}

QByteArray WaitSave::IntToArray(int v)
{
    int size = sizeof (int);

    QByteArray a;
    a.resize(size);

    for(int i = 0; i < size; i++){
        a[i] = static_cast<char>( (v >> ( (size - i -1) * 8) ) & 0xff );
    }

    return a;
}

QByteArray WaitSave::ShortToArray(unsigned short v)
{
    int size = sizeof (unsigned short);

    QByteArray a;
    a.resize(size);

    for(int i = 0; i < size; i++){
        a[i] = static_cast<char>( (v >> ( (size - i -1) * 8) ) & 0xff );
    }

    return a;
}

void WaitSave::setPoint(QList<QByteArray> *listTra)
{
    list = listTra;
}

void WaitSave::setData(bool *success_flag, axidma_dev_t dev, const array_t *chans, char *buf, axil_cmd_handle *cmd_user, unsigned char *mid0, int *name, unsigned int *Index, CameraSpace::CameraInfo Info)
{
    dma_success_flag = success_flag;
    axidma_dev = dev;
    rx_chans = chans;
    rx_buf = buf;
    axil_cmd_user = cmd_user;
    image_mid0 = mid0;
    fd_name = name;
    cameraIndex = Index;
    cameraInfo = Info;
    //    qDebug() << dma_success_flag << axidma_dev <<rx_chans <<rx_buf <<axil_cmd_user <<image_mid0 <<fd_name <<cameraIndex <<list ;
}

void WaitSave::updataData(unsigned short picStartX, unsigned short picStartY, unsigned short picWidth, unsigned short picHeight, unsigned char exposureMode, unsigned char saveLocation)
{
    cameraInfo.picStartX = picStartX;
    cameraInfo.picStartY = picStartY;
    cameraInfo.picWidth = picWidth;
    cameraInfo.picHeight = picHeight;
    cameraInfo.exposureMode = exposureMode;
    cameraInfo.saveLocation = saveLocation;
}

void WaitSave::SendPhotoMessage(QByteArray current_photo_message)
{
    //    qDebug() << current_photo_message;
    receive_photo_message_ = current_photo_message;
}

void WaitSave::SetDeviceNum(const unsigned char k_device_num)
{
    device_num_ = k_device_num;
}
